<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>学生成绩排行榜</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Arial', sans-serif;
      line-height: 1.6;
      color: #333;
      background-color: #f4f4f4;
      padding: 20px;
    }

    .container {
      max-width: 800px;
      margin: 0 auto;
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }

    h1 {
      text-align: center;
      color: #2c3e50;
      margin-bottom: 30px;
      padding-bottom: 10px;
      border-bottom: 2px solid #3498db;
    }

    .controls {
      margin-bottom: 20px;
      text-align: center;
    }

    button {
      background-color: #3498db;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 16px;
      margin: 0 10px;
      transition: background-color 0.3s;
    }

    button:hover {
      background-color: #2980b9;
    }

    .ranking-table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }

    .ranking-table th, .ranking-table td {
      padding: 12px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }

    .ranking-table th {
      background-color: #3498db;
      color: white;
    }

    .ranking-table tr:nth-child(even) {
      background-color: #f2f2f2;
    }

    .ranking-table tr:hover {
      background-color: #e8f4fd;
    }

    .rank {
      font-weight: bold;
      color: #2c3e50;
    }

    .score {
      font-weight: bold;
      color: #27ae60;
    }

    .loading {
      text-align: center;
      padding: 20px;
      color: #666;
    }

    .error {
      color: #e74c3c;
      text-align: center;
      padding: 20px;
    }

    .medal {
      display: inline-block;
      width: 20px;
      height: 20px;
      margin-right: 5px;
      border-radius: 50%;
    }

    .gold {
      background-color: #ffd700;
    }

    .silver {
      background-color: #c0c0c0;
    }

    .bronze {
      background-color: #cd7f32;
    }
  </style>
</head>
<body>
<div class="container">
  <h1>学生成绩排行榜</h1>

  <div class="controls">
    <button onclick="loadTopRanking(10)">前10名</button>
    <button onclick="loadTopRanking(20)">前20名</button>
    <button onclick="loadTopRanking(50)">前50名</button>
    <button style="background:#2ecc71" onclick="loadAll()">显示全部</button>
  </div>

  <div style="margin-top:20px;">
    <h2 style="margin-bottom:10px;">学生管理</h2>
    <div style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
      <input id="sid" placeholder="学号" style="padding:8px; width:140px;" />
      <input id="sname" placeholder="姓名" style="padding:8px; width:140px;" />
      <input id="sscore" type="number" placeholder="成绩" style="padding:8px; width:120px;" />
      <button onclick="upsertStudent()">新增/更新</button>
      <button style="background:#e67e22" onclick="deleteStudent()">删除</button>
      <button style="background:#16a085" onclick="refreshAll()">刷新排行榜</button>
      <button style="background:#8e44ad" onclick="queryRank()">查询排名</button>
    </div>
    <div id="rank-result" style="margin-top:10px; color:#8e44ad;"></div>
  </div>

  <div id="ranking-container">
    <div class="loading">加载中...</div>
  </div>
</div>

<script>
  const API_BASE_URL = 'http://localhost:8080';  // 指向Spring Boot服务

  // 页面加载时获取前10名
  window.onload = function() {
    loadTopRanking(10);
  };

  // 加载排行榜数据
  function loadTopRanking(topN) {
    const container = document.getElementById('ranking-container');
    container.innerHTML = '<div class="loading">加载中...</div>';

    fetch(`${API_BASE_URL}/api/ranking/top/${topN}`)
            .then(response => {
              if (!response.ok) {
                throw new Error('网络响应异常');
              }
              return response.json();
            })
            .then(data => {
              displayRanking(data);
            })
            .catch(error => {
              console.error('Error:', error);
              container.innerHTML = '<div class="error">加载失败: ' + error.message + '</div>';
            });
  }

  // 加载全部（从 DB 按分数降序）
  function loadAll() {
    const container = document.getElementById('ranking-container');
    container.innerHTML = '<div class="loading">加载中...</div>';
    fetch(`${API_BASE_URL}/api/ranking/all`)
      .then(response => {
        if (!response.ok) throw new Error('网络响应异常');
        return response.json();
      })
      .then(data => { displayRanking(data); })
      .catch(error => {
        console.error('Error:', error);
        container.innerHTML = '<div class="error">加载失败: ' + error.message + '</div>';
      });
  }

  function upsertStudent() {
    const studentId = document.getElementById('sid').value.trim();
    const studentName = document.getElementById('sname').value.trim();
    const scoreStr = document.getElementById('sscore').value.trim();
    if (!studentId) { alert('请填写学号'); return; }
    const payload = { studentId, studentName, score: scoreStr ? Number(scoreStr) : 0 };
    fetch(`${API_BASE_URL}/api/ranking/upsert`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    }).then(r => { if (!r.ok) throw new Error('保存失败'); return r; })
      .then(() => { alert('保存成功'); loadTopRanking(10); })
      .catch(e => alert(e.message));
  }

  function deleteStudent() {
    const studentId = document.getElementById('sid').value.trim();
    if (!studentId) { alert('请填写学号'); return; }
    fetch(`${API_BASE_URL}/api/ranking/delete/${encodeURIComponent(studentId)}`, { method: 'DELETE' })
      .then(r => r.json())
      .then(ok => { if (!ok) throw new Error('删除失败或学号不存在'); alert('删除成功'); loadTopRanking(10); })
      .catch(e => alert(e.message));
  }

  function refreshAll() {
    // 简单刷新：重新加载前10名
    loadTopRanking(10);
  }

  function queryRank() {
    const studentId = document.getElementById('sid').value.trim();
    if (!studentId) { alert('请填写学号'); return; }
    fetch(`${API_BASE_URL}/api/ranking/rank/${encodeURIComponent(studentId)}`)
      .then(r => r.json())
      .then(rank => {
        const el = document.getElementById('rank-result');
        if (rank === null) {
          el.textContent = '未上榜或暂无排名';
        } else {
          el.textContent = '当前排名：第 ' + rank + ' 名';
        }
      })
      .catch(() => { document.getElementById('rank-result').textContent = '查询失败'; });
  }

  // 显示排行榜
  function displayRanking(data) {
    const container = document.getElementById('ranking-container');

    if (!data || data.length === 0) {
      container.innerHTML = '<div class="error">暂无数据</div>';
      return;
    }

    let html = '<table class="ranking-table">';
    html += '<tr><th>排名</th><th>学号</th><th>姓名</th><th>成绩</th></tr>';

    data.forEach((student, index) => {
      const rank = index + 1;
      let medalClass = '';

      // 添加奖牌样式
      if (rank === 1) medalClass = 'gold';
      else if (rank === 2) medalClass = 'silver';
      else if (rank === 3) medalClass = 'bronze';

      html += '<tr>';
      html += `<td class="rank"><span class="medal ${medalClass}"></span>${rank}</td>`;
      html += `<td>${student.studentId}</td>`;
      html += `<td>${student.studentName}</td>`;
      html += `<td class="score">${student.score}</td>`;
      html += '</tr>';
    });

    html += '</table>';
    container.innerHTML = html;
  }
</script>
</body>
</html>
